// @flow
import React from 'react'
import styles from './InstallDocker.css'
import { Button, Progress, Icon, Modal } from 'antd'
import NoticeMessage from '../NoticeMessage'
import Table from '../Table'
import R from 'ramda'
type Props = {
  nextStep: Function,
  preStep: Function,
  kmxName: string
}

type State = {
  currentKmx: string,
  rowData: Array<Object>,
  visible: boolean,
  title: string,
  result: string,
  progressData: Object,
  disabled: boolean,
  refreshNode: Object
}
export default class InstallDocker extends React.Component {
  props: Props
  state: State
  detailCheck: Function
  stepClick: Function
  getInterval: number | null
  intervalProgress: () => void
  handleOk: () => void
  handleCancel: () => void
  getAllProgress: () => void
  refreshDockerInstall: () => void
  refreshStatus: () => void
  constructor (props: Props) {
    super(props)
    this.state = {
      currentKmx: '',
      rowData: [],
      visible: false,
      title: '',
      result: '',
      progressData: {},
      disabled: true,
      refreshNode: {}
    }
    this.detailCheck = this.detailCheck.bind(this)
    this.stepClick = this.stepClick.bind(this)
    this.intervalProgress = this.intervalProgress.bind(this)
    this.handleCancel = this.handleCancel.bind(this)
    this.handleOk = this.handleOk.bind(this)
    this.getAllProgress = this.getAllProgress.bind(this)
    this.refreshDockerInstall = this.refreshDockerInstall.bind(this)
    this.refreshStatus = this.refreshStatus.bind(this)
  }

  componentWillReceiveProps (nextProps: Object) {
    if (!R.equals(nextProps.kmxName, this.props.kmxName)) {
      this.setState({
        currentKmx: nextProps.kmxName
      })
      // this.getDockerProgress(nextProps.kmxName)
      this.intervalProgress(nextProps.kmxName)
    }
    // console.info(nextProps)
  }

  // progress function
  intervalProgress (name: string) {
    // this.getDockerProgress(name)
    const that = this
    this.getInterval = setInterval(function () {
      that.getDockerProgress(name)
    }, 2000)
  }

  handleCancel () {
    this.setState({
      visible: false
    })
  }

  handleOk () {
    this.setState({
      visible: false
    })
  }

  // 获取所有CM主机
  getAllCmMac (name: string) {
    const url = `${__CM_URL__}kmxes/${name}/cm/allHosts`
    fetch(url)
    .then((response) => {
      if (!(response.status >= 200 && response.status < 300) || response.status === 304) {
        console.error(response.status)
      }
      return response.json()
    })
    .then((json) => {
      if (json.code === 1) {
        throw new Error(json.message, 'InstallDocker.js')
      }
      console.info(json)
      this.setState({ rowData: json.body.items })
    })
    .catch((err) => {
      console.info(err)
      new NoticeMessage().createNotice({
        type: 'error',
        title: '错误提示',
        message: (err && err.message) ? err.message : err })
    })
  }

  // 获取所有docker的安装进度
  getDockerProgress (name: string) {
    console.info('interval run this...')
    const url = `${__CM_URL__}kmxes/${name}/installDocker`
    fetch(url)
    .then((response) => {
      if (!(response.status >= 200 && response.status < 300) || response.status === 304) {
        console.error(response.status)
      }
      return response.json()
    })
    .then((json) => {
      if (json.code === 1) {
        throw new Error(json.message, 'InstallDocker.js')
      }
      console.info(json)
      // R.filter(x => x.completed, json.body.items)
      // console.info(json.body.items.map(x => x.completed))
      if (json.body.items.map(x => x.completed).indexOf(false) === -1) {
        if (this.getInterval) {
          clearInterval(this.getInterval)
          this.getInterval = null
        }
        if (json.body.items.map(x => x.error).join('') === '') {
          this.getInterval = setInterval(() => {
            this.getAllProgress()
          }, 2000)
        }
      }
      this.setState({ rowData: json.body.items })
    })
    .catch((err) => {
      console.error(err)
      if (this.getInterval) {
        clearInterval(this.getInterval)
        this.getInterval = null
      }
      new NoticeMessage().createNotice({
        type: 'error',
        title: '错误提示',
        message: (err && err.message) ? err.message : err })
    })
  }

  // 获取总进度条
  getAllProgress () {
    const url = `${__CM_URL__}kmx/loadImages`
    fetch(url)
    .then((response) => {
      if (!(response.status >= 200 && response.status < 300) || response.status === 304) {
        console.error(response.status)
      }
      return response.json()
    })
    .then((json) => {
      if (json.code === 1) {
        throw new Error(json.message, 'InstallDocker.js')
      }
      this.setState({
        progressData: json.body
      })
      if (json.body.error === '' && json.body.total === json.body.progress) {
        if (this.getInterval) {
          clearInterval(this.getInterval)
          this.getInterval = null
          this.setState({ disabled: false })
        }
      }
    })
    .catch((err) => {
      console.error(err)
      if (this.getInterval) {
        clearInterval(this.getInterval)
        this.getInterval = null
      }
      new NoticeMessage().createNotice({
        type: 'error',
        title: '错误提示',
        message: (err && err.message) ? err.message : err })
    })
  }

  // 刷新单个docker安装进度
  refreshDockerInstall (name: string, hostName: string) {
    const url = `${__CM_URL__}kmxes/${name}/installDocker?hostname=${hostName}`
    fetch(url)
    .then((response) => {
      if (!(response.status >= 200 && response.status < 300) || response.status === 304) {
        console.error(response.status)
      }
      return response.json()
    })
    .then((json) => {
      if (json.code === 1) {
        throw new Error(json.message, 'InstallDocker.js')
      }
      this.setState({ refreshNode: json.body })
    })
    .catch((err) => {
      console.error(err)
      new NoticeMessage().createNotice({
        type: 'error',
        title: '错误提示',
        message: (err && err.message) ? err.message : err })
    })
  }

  detailCheck (params: Object) {
    console.info(params)
    this.setState({
      visible: true,
      title: params.data.error,
      result: JSON.stringify(params.data.result, null, 4)
    })
  }

  stepClick (str: string) {
    if (str === 'pre') {
      this.props.preStep(2)
    }
    if (str === 'next') {
      this.props.nextStep(4)
    }
  }

  refreshStatus (params: Object) {
    // console.info(params)
    this.refreshDockerInstall(this.props.kmxName, params.data.hostname)
  }

  render () {
    const columnDefs = [
      {
        headerName: '主机',
        field: 'hostname',
        suppressMenu: true,
        cellStyle: { padding: '8px', textAlign: 'center' }
      },
      {
        headerName: '状态',
        field: 'error',
        suppressMenu: true,
        width: 300,
        cellStyle: { padding: '8px' },
        cellRendererFramework: (params: Object) => {
          return <Progress percent={(params.data.progress / params.data.total) * 100} showInfo={false}
            strokeWidth={25} status={params.value !== '' ? 'exception' : 'success'} />
        }
      },
      {
        headerName: '报告',
        field: 'text',
        suppressMenu: true,
        cellStyle: { padding: '8px', textAlign: 'center' },
        cellRendererFramework: (params: Object) => {
          if (params.data.status === 'success') {
            return <div className={styles['link']}><a onClick={this.detailCheck}>详细报告</a></div>
          } else {
            return <div className={styles['link']}>
              <a onClick={() => { this.detailCheck(params) }}
                style={{ textDecoration: params.data.error === '' ? 'line-through' : 'none' }}
                disabled={params.data.error === ''}>详细报告</a>
              <p>
                {
                  params.data.error === ''
                    ? null
                  : <Icon type='sync' onClick={() => { this.refreshStatus(params) }} />
                }
              </p>
            </div>
          }
        }
      }
    ]
    const { rowData, visible, title, result, progressData, disabled, refreshNode } = this.state
    return (
      <div className={styles['content']}>
        <div className={styles['main']}>
          <div className={styles['table']}>
            <Table
              columnDefs={columnDefs}
              rowData={rowData}
              currentMess={refreshNode}
            />
          </div>
          <div className={styles['progress']}>
            <Progress percent={R.isEmpty(progressData) ? 0 : (progressData.progress / progressData.total) * 100}
              showInfo={false} strokeWidth={25} status='active' />
          </div>
        </div>
        <div className={styles['btn']}>
          <div style={{ float: 'right' }}>
            {
              // <Button onClick={() => { this.stepClick('pre') }} disabled={disabled}>上一步</Button> &emsp;
            }
            <Button onClick={() => { this.stepClick('next') }} disabled={disabled} type='primary'>下一步</Button>
          </div>
        </div>
        <Modal visible={visible}
          title={title}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          style={{
            top: '20%'
          }}
          footer={[
            <Button key='back' size='small' onClick={this.handleOk}>确定</Button>
          ]}>
          <p>{result}</p>
        </Modal>
      </div>
    )
  }
}
